import { useState } from 'react'
import './ConditionalRendering.css'

// 基本条件渲染 - 使用 if 语句
function BasicIfExample() {
  const [isLoggedIn, setIsLoggedIn] = useState(false)
  const [userRole, setUserRole] = useState('guest')

  const handleLogin = () => {
    setIsLoggedIn(true)
    setUserRole('user')
  }

  const handleLogout = () => {
    setIsLoggedIn(false)
    setUserRole('guest')
  }

  const handleUpgrade = () => {
    setUserRole('admin')
  }

  let content
  if (!isLoggedIn) {
    content = (
      <div className="auth-status">
        <h3>请先登录</h3>
        <button onClick={handleLogin}>登录</button>
      </div>
    )
  } else if (userRole === 'admin') {
    content = (
      <div className="auth-status">
        <h3>欢迎管理员!</h3>
        <p>您拥有完全访问权限</p>
        <button onClick={handleLogout}>退出</button>
      </div>
    )
  } else {
    content = (
      <div className="auth-status">
        <h3>欢迎回来!</h3>
        <p>普通用户权限</p>
        <button onClick={handleUpgrade}>升级为管理员</button>
        <button onClick={handleLogout}>退出</button>
      </div>
    )
  }

  return (
    <div className="example-container">
      <h4>基本 if 条件渲染</h4>
      {content}
    </div>
  )
}

// 三元运算符示例
function TernaryExample() {
  const [temperature, setTemperature] = useState(20)
  const [isOnline, setIsOnline] = useState(true)

  const getTemperatureColor = (temp) => {
    return temp > 30 ? 'hot' : temp > 10 ? 'normal' : 'cold'
  }

  return (
    <div className="example-container">
      <h4>三元运算符条件渲染</h4>
      
      <div className="controls">
        <label>
          温度: 
          <input 
            type="range" 
            min="-10" 
            max="50" 
            value={temperature}
            onChange={(e) => setTemperature(Number(e.target.value))}
          />
          <span>{temperature}°C</span>
        </label>
        
        <label>
          <input 
            type="checkbox" 
            checked={isOnline}
            onChange={(e) => setIsOnline(e.target.checked)}
          />
          在线状态
        </label>
      </div>

      <div className={`temperature-display ${getTemperatureColor(temperature)}`}>
        <p>
          温度状态: {temperature > 30 ? '炎热' : temperature > 10 ? '适宜' : '寒冷'}
        </p>
      </div>

      <div className={`status-indicator ${isOnline ? 'online' : 'offline'}`}>
        <p>
          连接状态: {isOnline ? '🟢 在线' : '🔴 离线'}
        </p>
      </div>
    </div>
  )
}

// 逻辑与运算符示例
function LogicalAndExample() {
  const [notifications, setNotifications] = useState([
    { id: 1, message: '新消息', read: false },
    { id: 2, message: '系统更新', read: true },
    { id: 3, message: '安全提醒', read: false }
  ])
  
  const [unreadCount, setUnreadCount] = useState(2)
  const [showSettings, setShowSettings] = useState(false)

  const markAsRead = (id) => {
    setNotifications(prev => 
      prev.map(notif => 
        notif.id === id ? { ...notif, read: true } : notif
      )
    )
    setUnreadCount(prev => Math.max(0, prev - 1))
  }

  const clearAll = () => {
    setNotifications([])
    setUnreadCount(0)
  }

  return (
    <div className="example-container">
      <h4>逻辑与运算符条件渲染</h4>
      
      <div className="notification-panel">
        <div className="notification-header">
          <h5>通知中心</h5>
          <div className="notification-controls">
            <button onClick={() => setShowSettings(!showSettings)}>
              {showSettings ? '隐藏设置' : '显示设置'}
            </button>
            {unreadCount > 0 && (
              <button onClick={clearAll} className="clear-button">
                清空所有
              </button>
            )}
          </div>
        </div>

        {unreadCount > 0 && (
          <div className="unread-badge">
            您有 {unreadCount} 条未读消息
          </div>
        )}

        <div className="notification-list">
          {notifications.map(notif => (
            <div 
              key={notif.id} 
              className={`notification-item ${notif.read ? 'read' : 'unread'}`}
            >
              <span className="notification-message">{notif.message}</span>
              {!notif.read && (
                <button 
                  onClick={() => markAsRead(notif.id)}
                  className="mark-read-btn"
                >
                  标记已读
                </button>
              )}
            </div>
          ))}
        </div>

        {notifications.length === 0 && (
          <div className="empty-state">
            <p>暂无通知</p>
          </div>
        )}

        {showSettings && (
          <div className="settings-panel">
            <h5>通知设置</h5>
            <label>
              <input type="checkbox" defaultChecked />
              启用桌面通知
            </label>
            <label>
              <input type="checkbox" defaultChecked />
              启用声音提醒
            </label>
          </div>
        )}
      </div>
    </div>
  )
}

// 复杂条件渲染示例
function ComplexConditionalExample() {
  const [user, setUser] = useState({
    name: '',
    age: '',
    membership: 'none',
    hasPremium: false
  })

  const [products] = useState([
    { id: 1, name: '基础课程', price: 99, level: 'basic' },
    { id: 2, name: '进阶课程', price: 199, level: 'advanced' },
    { id: 3, name: 'VIP课程', price: 399, level: 'vip' }
  ])

  const updateUser = (field, value) => {
    setUser(prev => ({ ...prev, [field]: value }))
  }

  const getAvailableProducts = () => {
    if (user.age === '') return []
    
    const age = Number(user.age)
    if (age < 18) {
      return products.filter(p => p.level === 'basic')
    } else if (age < 25) {
      return products.filter(p => p.level === 'basic' || p.level === 'advanced')
    } else {
      return products
    }
  }

  const canAccessProduct = (product) => {
    if (!user.name || !user.age) return false
    
    const age = Number(user.age)
    if (product.level === 'vip' && !user.hasPremium) return false
    if (product.level === 'advanced' && age < 18) return false
    if (product.level === 'basic' && age < 16) return false
    
    return true
  }

  const availableProducts = getAvailableProducts()

  return (
    <div className="example-container">
      <h4>复杂条件渲染</h4>
      
      <div className="user-form">
        <h5>用户信息</h5>
        <div className="form-row">
          <input 
            type="text" 
            placeholder="姓名"
            value={user.name}
            onChange={(e) => updateUser('name', e.target.value)}
          />
          <input 
            type="number" 
            placeholder="年龄"
            value={user.age}
            onChange={(e) => updateUser('age', e.target.value)}
            min="1"
            max="100"
          />
        </div>
        
        <div className="form-row">
          <label>
            <input 
              type="checkbox" 
              checked={user.hasPremium}
              onChange={(e) => updateUser('hasPremium', e.target.checked)}
            />
            VIP会员
          </label>
        </div>
      </div>

      <div className="products-section">
        <h5>可用课程</h5>
        {user.name && user.age ? (
          <div className="products-grid">
            {availableProducts.map(product => (
              <div 
                key={product.id} 
                className={`product-card ${!canAccessProduct(product) ? 'disabled' : ''}`}
              >
                <h6>{product.name}</h6>
                <p className="price">¥{product.price}</p>
                {canAccessProduct(product) ? (
                  <button className="buy-button">购买</button>
                ) : (
                  <div className="restriction">
                    {product.level === 'vip' && !user.hasPremium && '需要VIP会员'}
                    {product.level === 'advanced' && Number(user.age) < 18 && '需要年满18岁'}
                    {product.level === 'basic' && Number(user.age) < 16 && '需要年满16岁'}
                  </div>
                )}
              </div>
            ))}
          </div>
        ) : (
          <div className="please-login">
            <p>请填写用户信息查看可用课程</p>
          </div>
        )}
      </div>

      {user.name && user.age && (
        <div className="user-summary">
          <h5>用户状态总结</h5>
          <p>
            姓名: <strong>{user.name}</strong> | 
            年龄: <strong>{user.age}</strong> | 
            会员: <strong>{user.hasPremium ? 'VIP' : '普通'}</strong>
          </p>
          <p>
            可访问课程数: <strong>{availableProducts.length}</strong>
          </p>
        </div>
      )}
    </div>
  )
}

// 防止组件渲染
function PreventRenderExample() {
  const [showComponent, setShowComponent] = useState(true)
  const [data, setData] = useState(null)

  const loadData = () => {
    setData('数据加载完成!')
  }

  const ExpensiveComponent = () => {
    console.log('ExpensiveComponent 被渲染了')
    return (
      <div className="expensive-component">
        <h4>昂贵的组件</h4>
        <p>这个组件包含复杂的计算逻辑</p>
        <p>当前数据: {data || '暂无数据'}</p>
      </div>
    )
  }

  return (
    <div className="example-container">
      <h4>防止组件渲染</h4>
      
      <div className="controls">
        <button onClick={() => setShowComponent(!showComponent)}>
          {showComponent ? '隐藏组件' : '显示组件'}
        </button>
        <button onClick={loadData}>加载数据</button>
        <button onClick={() => setData(null)}>清空数据</button>
      </div>

      <div className="render-area">
        {showComponent && <ExpensiveComponent />}
        
        {!showComponent && (
          <div className="component-hidden">
            <p>组件已隐藏，不会进行渲染</p>
          </div>
        )}
      </div>
    </div>
  )
}

function ConditionalRendering() {
  return (
    <div className="example-page">
      <div className="example-header">
        <h1>条件渲染</h1>
        <p>学习 React 中的条件渲染技术，包括 if 语句、三元运算符和逻辑与运算符</p>
      </div>

      <div className="example-section">
        <h2>1. 使用 if 语句进行条件渲染</h2>
        <p>在 JavaScript 中使用 if 语句决定渲染哪个组件：</p>
        
        <div className="code-block">
{`function AuthStatus({ isLoggedIn, userRole }) {
  let content
  if (!isLoggedIn) {
    content = <LoginPrompt />
  } else if (userRole === 'admin') {
    content = <AdminPanel />
  } else {
    content = <UserPanel />
  }
  
  return <div>{content}</div>
}`}
        </div>

        <BasicIfExample />
      </div>

      <div className="example-section">
        <h2>2. 使用三元运算符</h2>
        <p>使用三元运算符进行简单的条件选择：</p>
        
        <div className="code-block">
{`function TemperatureDisplay({ temperature }) {
  return (
    <div className={temperature > 30 ? 'hot' : 'normal'}>
      {temperature > 30 ? '太热了!' : '温度适宜'}
    </div>
  )
}`}
        </div>

        <TernaryExample />
      </div>

      <div className="example-section">
        <h2>3. 使用逻辑与运算符</h2>
        <p>使用 && 运算符进行条件渲染：</p>
        
        <div className="code-block">
{`function Notification({ message, unreadCount }) {
  return (
    <div>
      {unreadCount > 0 && (
        <span className="badge">
          {unreadCount} 条未读消息
        </span>
      )}
      {message && <p>{message}</p>}
    </div>
  )
}`}
        </div>

        <LogicalAndExample />
      </div>

      <div className="example-section">
        <h2>4. 复杂条件渲染</h2>
        <p>结合多种条件进行复杂的渲染逻辑：</p>
        
        <ComplexConditionalExample />
      </div>

      <div className="example-section">
        <h2>5. 防止组件渲染</h2>
        <p>使用条件来防止不必要的组件渲染：</p>
        
        <div className="code-block">
{`function ExpensiveComponent({ shouldRender }) {
  // 只有在 shouldRender 为 true 时才渲染
  return shouldRender ? (
    <ComplexComponent />
  ) : null
}`}
        </div>

        <PreventRenderExample />
      </div>

      <div className="tip">
        <strong>条件渲染最佳实践：</strong>
        <ul>
          <li>对于简单条件，优先使用三元运算符</li>
          <li>对于复杂条件，使用 if 语句在组件外部处理</li>
          <li>使用 && 运算符处理可选内容的渲染</li>
          <li>避免在 JSX 中编写过于复杂的条件逻辑</li>
          <li>考虑将复杂条件逻辑提取到单独的函数中</li>
          <li>使用 null 或 Fragment 来防止不必要的 DOM 元素</li>
        </ul>
      </div>
    </div>
  )
}

export default ConditionalRendering